package com.woniu.controller;

import com.github.pagehelper.PageInfo;
import com.woniu.common.CommonResult;
import com.woniu.exception.RoleServiceException;
import com.woniu.pojo.Roles;
import com.woniu.service.RolesService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.Transformer;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Controller
@RequestMapping("/roles")
@Api(tags = "角色管理")
public class RolesController {

    @Autowired
    private RolesService rolesService;

    @RequestMapping("/list")
    @ResponseBody
    @RequiresPermissions("sys:role:list")
    @ApiOperation(value = "分页查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "currentPage",value = "当前页数",defaultValue = "1"),
            @ApiImplicitParam(name = "pageSize",value = "每页数据条数",defaultValue = "5")
    })
    public CommonResult list(@RequestParam(value="page",defaultValue = "1",required = false)Integer currentPage,
                             @RequestParam(value = "limit",defaultValue = "5",required = false)Integer pageSize){
        List<Roles> roles = rolesService.findByPage(currentPage,pageSize);
        PageInfo info = new PageInfo(roles);
        return CommonResult.success(info);
    }


    /**
     * 添加角色并授权
     * @param roles 要添加的角色对象
     * @param menuId  当前角色被授权的菜单id字符串，以逗号分隔的字符串
     * @return
     */
    @PostMapping("/saveRole")
    @ResponseBody
    @RequiresPermissions("sys:role:save")
    @ApiOperation(value = "添加角色并授权")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "roles",value = "角色信息"),
            @ApiImplicitParam(name = "menuId",value = "菜单ID",dataType = "Integer")
    })
    public  CommonResult saveRole(Roles roles,String menuId){
        //检查角色的名称不能重复
        Roles result = rolesService.findByRoleName(roles.getRoleName());

        if (result != null) {
            return CommonResult.failed("角色名称已经存在，不能重复添加");
        }

        //List<Long> keys = Arrays.stream(menuId.split(",")).map(s->Long.parseLong(s)).collect(Collectors.toList());
        List<String> keysStringList = Arrays.asList(menuId.split(","));
        List<Integer> keys = new ArrayList<>();
        CollectionUtils.collect(keysStringList, new Transformer() {
            @Override
            public Object transform(Object o) {
                return Integer.valueOf(o.toString());
            }
        }, keys);
        try {
            rolesService.saveRole(roles,keys);
            return CommonResult.success("添加成功");
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResult.failed("添加失败");
        }
    }

    /**
     * 导航到编辑页面
     * @param id
     * @return
     */
    @GetMapping("/editRole/{id}")
    @ApiOperation(value = "导航到编辑页面")
    @ApiImplicitParam(name = "id",value = "角色ID",dataType = "Integer")
    public ModelAndView editRole(@PathVariable("id")Integer id){
        Roles roles = rolesService.findById(id);
        ModelAndView modelAndView = new ModelAndView("/sys/editRole");
        modelAndView.addObject("roles",roles);
        return modelAndView;
    }

    /**
     * 编辑角色
     * @return
     */
    @PutMapping("/updateRole")
    @ResponseBody
    @RequiresPermissions("sys:role:update")
    @ApiOperation(value = "编辑角色")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "roles",value = "编辑后的角色信息"),
            @ApiImplicitParam(name = "menuId",value = "菜单ID",dataType = "Integer")
    })
    public CommonResult updateRole(Roles roles,String menuId){

        //检查更新的角色名称是否已经存
        if(rolesService.checkRoleName(roles)){
            return CommonResult.failed("该角色名称已经存在");
        }
        List<String> StringList = Arrays.asList(menuId.split(","));
        List<Integer> keys = new ArrayList<>();
        CollectionUtils.collect(StringList, new Transformer() {
            @Override
            public Object transform(Object o) {
                return Integer.valueOf(o.toString());
            }
        }, keys);

        try {
            rolesService.updateRole(roles,keys);
            return CommonResult.success("编辑成功");
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResult.failed("编辑失败");
        }

    }

    /**
     * 删除角色
     * @param roleId
     * @return
     */
    @DeleteMapping("/del/{id}")
    @ResponseBody
    @RequiresPermissions("sys:role:delete")
    @ApiOperation(value = "删除角色")
    @ApiImplicitParam(name = "id",value = "角色ID",dataType = "Integer")
    public CommonResult del(@PathVariable("id")Integer roleId){
        try {
            rolesService.delRole(roleId);
            return CommonResult.success("删除成功");
        } catch (RoleServiceException e) {
            e.printStackTrace();
            return CommonResult.failed(e.getMessage());
        }catch (Exception e) {
            e.printStackTrace();
            return CommonResult.failed("删除失败");
        }
    }

    /**
     * 批量删除角色
     * @param keys
     * @return
     */
    @DeleteMapping("/batchDel/{keys}")
    @ResponseBody
    @RequiresPermissions("sys:role:delete")
    @ApiOperation(value = "批量删除角色")
    @ApiImplicitParam(name = "keys",value ="角色ID字符串" )
    public CommonResult batchDel(@PathVariable("keys")String keys){
        //List<Long> rolesId =Arrays.stream(keys.split(",")).map(s->Long.parseLong(s)).collect(Collectors.toList());
        List<String> keysStringList = Arrays.asList(keys.split(","));
        List<Integer> rolesId = new ArrayList<>();
        CollectionUtils.collect(keysStringList, new Transformer() {
            @Override
            public Object transform(Object o) {
                return Integer.valueOf(o.toString());
            }
        }, rolesId);
        try {
            rolesService.batchDel(rolesId);
            return CommonResult.success("删除成功");
        } catch (RoleServiceException e) {
            e.printStackTrace();
            return CommonResult.failed(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResult.failed("删除失败");
        }
    }


}
